<template>
  <div class="changeInput">
    <el-input v-model="inputInfo"></el-input>
    <el-button class="changeInput-button" @click="changeInput">转换</el-button>
    <div>{{ outPut }}</div>
    <div class="changeInput-content"></div>
    <div class="map-chart" ref="mapChart"></div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import pinyin from "pinyin";
import * as Echarts from "echarts";
import "echarts-gl";
import shanxi from "./shanxi.json";
import textures from "./textture.jpg";
const inputInfo = ref("");
const outPut = ref("我是转换成功的数据");
function convertMixedInputToTableName(input) {
  // 分割输入为中文和非中文部分
  let chineseParts = input.match(/[\u4e00-\u9fa5]+/g) || [];
  let nonChineseParts = input.split(/[\u4e00-\u9fa5]+/).filter(Boolean);

  // 转换中文部分为拼音
  let pinyinParts = chineseParts.map((part) =>
    pinyin(part, { style: pinyin.STYLE_NORMAL })
      .map(([pinyin]) => pinyin)
      .join("_")
  );

  // 处理非中文部分，去除不允许的字符
  nonChineseParts = nonChineseParts.map((part) =>
    part.replace(/[^a-zA-Z0-9]/g, "").toLowerCase()
  );

  // 合并所有部分，使用下划线连接
  let tableNameParts = pinyinParts.concat(nonChineseParts).filter(Boolean);
  let tableName = tableNameParts.join("_");

  // 确保表名首字符合规
  if (!tableName.match(/^[a-z_]/i)) {
    tableName = "_" + tableName;
  }

  return tableName;
}
const changeInput = () => {
  outPut.value = convertMixedInputToTableName(inputInfo.value);
};

function addPinyinToText(text) {
  const containerOuter = document.createElement("div");
  containerOuter.classList.add("outer");

  for (let i = 0; i < text.length; i++) {
    const container = document.createElement("span");
    container.classList.add("book-pinyin-container");

    const char = text[i];
    // 判断是否是中文
    let chineseParts = char.match(/[\u4e00-\u9fa5]+/g) || [];

    const pinyinList = pinyin(chineseParts.join(""));

    // 如果有拼音，则创建并添加拼音的span
    if (pinyinList.length > 0) {
      const pinyinStr = pinyinList.map((pinyinArr) => pinyinArr[0]).join("");
      const pinyinSpan = document.createElement("span");
      pinyinSpan.textContent = pinyinStr;
      pinyinSpan.classList.add("pinyin");
      container.appendChild(pinyinSpan);
    }
    // 创建中文字符的span
    const chineseCharSpan = document.createElement("span");
    chineseCharSpan.textContent = char;
    chineseCharSpan.classList.add("chinese-character");
    container.appendChild(chineseCharSpan);
    containerOuter.appendChild(container);
  }

  return containerOuter;
}

const initChart = () => {
  const mapChart = Echarts.init(document.querySelector(".map-chart"));
  mapChart.onresize = mapChart.resize;
  Echarts.registerMap("shanxi", shanxi);
  let centerArr = [];
  let locationArr = [];
  shanxi.features.forEach((item) => {
    centerArr.push({
      name: item.properties.name,
      value: item.properties.centroid.concat(
        (Math.random() * 100 + 50).toFixed(2)
      ),
    });
    locationArr.push({
      name: item.properties.name,
      value: item.properties.centroid.concat(0),
    });
  });

  let seriesData = shanxi.features.map((item) => {
    let aq = Math.floor(Math.random() * 101);
    return {
      name: item.properties.name,
      adcode: item.properties.adcode,
      center: item.properties.centroid,
      Installed: parseInt(Math.random() * 1000),
      uninstalled: parseInt(Math.random() * 1000),
      finishing: aq,
      value: aq,
    };
  });

  // 动态计算柱形图的高度
  const lineMaxHeight = () => {
    const maxValue = Math.max(...seriesData.map((item) => item.value));
    return 0.5 / maxValue;
  };

  // 柱状体的主干
  const lineData = seriesData.map((item) => {
    let coords = [
      item.center,
      [item.center[0], item.center[1] + item.value * lineMaxHeight()],
    ];
    return {
      coords,
      name: item.name,
      Installed: item.Installed,
      uninstalled: item.uninstalled,
      finishing: item.finishing,
    };
  });

  // 柱状体的顶部
  const scatterTopData = seriesData.map((item) => {
    let coords = [
      item.center[0],
      item.center[1] + item.value * lineMaxHeight(),
      item.value,
    ];
    return {
      name: item.name,
      value: coords,
      Installed: item.Installed,
      uninstalled: item.uninstalled,
      finishing: item.finishing,
    };
  });

  // 柱状体的底部
  const scatterBottomData = seriesData.map((item) => {
    return {
      name: item.name,
      value: item.center,
      Installed: item.Installed,
      uninstalled: item.uninstalled,
      finishing: item.finishing,
    };
  });
  console.log(444, centerArr);
  const options = {
    geo: {
      show: false, // 不显示地图，用于为动效散点提供2D地图坐标系
      map: "shanxi",
      type: "map",
      data: centerArr,
      roam: false, // 禁用缩放、拖拽
      // layoutCenter: ['50%', '47%'], // 地图中心位置
      // layoutSize: '90%', // 控制地图尺寸（地图的宽度和高度都会改变）
      // aspectScale: 0.78, // 控制地图长宽比（此值越小地图越窄，越大地图越宽）
      // aspectScale: 1.8,
      zlevel: 1,
    },
    geo3D: {
      show: true,
      name: "山西",
      type: "map3D",
      map: "shanxi",
      aspectScale: 0.9,
      selectedMode: false,
      shading: "realistic",
      itemStyle: {
        opacity: 1,
        borderWidth: 2,
        borderColor: "#37957C",
        shadowColor: "red",
      },
      // 初始角度
      viewControl: {
        alpha: 90, // 上下旋转角度，范围是 [-90, 90]
        beta: -4, // 左右旋转角度，范围是 [-180, 180]
        distance: 220, // 视距（摄像机到观察对象的距离）
        // minDistance: 50, // 最小视距
        // maxDistance: 300, // 最大视距
        rotateSensitivity: 0, // 禁用旋转
        panSensitivity: 0, // 禁用平移
        zoomSensitivity: 0, // 禁用缩放
      },
      //纹理
      realisticMaterial: {
        detailTexture: textures,
        textureTiling: 1, // 纹理平铺，1是拉伸，数字表示纹理平铺次数
        roughness: 1, // 材质粗糙度，0完全光滑，1完全粗糙
        metalness: 0, // 0材质是非金属 ，1金属
        roughnessAdjust: 0,
      },
      //hover
      emphasis: {
        label: {
          show: true,
          color: "#FFF",
          fontSize: 20,
        },
        itemStyle: {
          borderColor: "#41EB26",
          borderWidth: 5,
          color: "#41EB26",
        },
      },
      zlevel: 2,
    },
    //绘制柱子
    series: [
      {
        // 动效散点图层，使用2D地图坐标系
        type: "effectScatter",
        coordinateSystem: "geo",
        zlevel: 3,
        rippleEffect: {
          //涟漪特效
          period: 4, //动画时间，值越小速度越快
          brushType: "stroke", //波纹绘制方式 stroke, fill
          scale: 10, //波纹圆环最大限制，值越大波纹越大
          // scale: 2, //动画中波纹的最大缩放比例，值越大波纹越大 4
          color: "rgb(34,238,252,0.4)", //涟漪的颜色
          number: 2, //波纹的数量
        },
        symbol: "circle",
        symbolSize: [8, 4],
        itemStyle: {
      color: {
        type: 'radial',
        x: 0.5,
        y: 0.5,
        r: 0.5,
        colorStops: [
          {
            offset: 0,
            color: 'rgb(34,238,252, 0)' // 0% 处的颜色
          },
          {
            offset: 0.74,
            color: 'rgb(34,238,252, 0)' // 100% 处的颜色
          },
          {
            offset: 0.75,
            color: 'rgb(34,238,252, 0.16)' // 100% 处的颜色
          },
          {
            offset: 1,
            color: 'rgb(34,238,252, 0.16)' // 100% 处的颜色
          }
        ]
      }
    },
        data: centerArr,
      },
      // 柱状体的主干
      {
        type: "lines",
        zlevel: 5,
        effect: {
          show: false,
          symbolSize: 5, // 图标大小
        },
        lineStyle: {
          width: 14.5, // 尾迹线条宽度
          color: "rgb(22,255,255, .6)",
          opacity: 1, // 尾迹线条透明度
          curveness: 0, // 尾迹线条曲直度
        },
        silent: false,
        data: lineData,
        tooltip: {
          show: true,
        },
      },
      // 柱状体的顶部
      {
        type: "scatter",
        coordinateSystem: "geo",
        geoIndex: 0,
        zlevel: 5,
        label: {
          show: false,
          formatter: function (e) {
            return `数值：${e.data[2]}`;
          },
          position: "top",
        },
        symbol: "circle",
        symbolSize: [14, 6],
        itemStyle: {
          color: "rgb(22,255,255, 1)",
          opacity: 1,
        },
        silent: true,
        data: scatterTopData,
        tooltip: { show: false },
      },
      // 柱状体的底部
      {
        type: "scatter",
        coordinateSystem: "geo",
        geoIndex: 0,
        zlevel: 4,
        label: {
          show: true,
          color: "rgba(255,255,255,0.8)",
          fontSize: 10,
          formatter: "{b}",
          position: "bottom",
          fontSize: 10,
          distance: 10,
        },
        symbol: "circle",
        symbolSize: [14, 6],
        itemStyle: {
          color: "#22EEFC",
          opacity: 1,
        },
        silent: false,
        data: scatterBottomData,
        tooltip: {
          show: true,
        },
      },
      // {
      //   name: "bar3D",
      //   type: "bar3D",
      //   coordinateSystem: "geo3D",
      //   barSize: 1, //柱子粗细
      //   shading: "lambert",
      //   opacity: 1,
      //   bevelSize: 0.3,
      //   data: centerArr,
      // },
      // {
      //   type: "scatter3D",
      //   coordinateSystem: "geo3D",
      //   symbol: "circle",
      //   symbolSize: 15,
      //   itemStyle: {
      //     color: "#ff9900",
      //     opacity: 0.8,
      //   },
      //   data: locationArr,
      // },
    ],
  };
  mapChart.setOption(options);
};

onMounted(() => {
  const text = "我是一个测试";
  const pinyinContainer = addPinyinToText(text);
  let contentDiv = document.getElementsByClassName("changeInput-content")[0];
  // 将生成的拼音容器添加到页面中
  contentDiv.appendChild(pinyinContainer);

  //初始化地图
  initChart();
});
</script>

<style lang="scss">
.changeInput {
  display: flex;
  flex-direction: column;
  gap: 10px;

  .map-chart {
    width: 100%;
    height: 500px;
  }

  &-button {
    width: 100px;
  }

  &-content {
    display: flex;
    flex-wrap: wrap;
    width: 100%;
  }

  .book-pinyin-container {
    display: inline-block;
    text-align: center;
    width: 28px;

    .chinese-character {
      display: inline-block;
      width: 28px;
      margin-bottom: 3px; /* 调整间距以适应拼音 */
    }

    .pinyin {
      display: inline-block;
      width: 28px;
      font-size: 10px;
      text-align: center;
    }
  }
}
</style>
